package com.kkb.cubemall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kkb.cubemall.common.utils.PageUtils;
import com.kkb.cubemall.common.utils.Query;
import com.kkb.cubemall.product.dao.AttrGroupDao;
import com.kkb.cubemall.product.entity.AttrEntity;
import com.kkb.cubemall.product.entity.AttrGroupEntity;
import com.kkb.cubemall.product.service.AttrGroupService;
import com.kkb.cubemall.product.service.AttrService;
import com.kkb.cubemall.product.vo.AttrGroupWithAttrsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<>();
        Integer categoryId = (Integer) params.get("categoryId");
        String key = (String) params.get("key");
        if (categoryId != 0) {
            queryWrapper.eq("category_id", categoryId);
        }
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(qw -> qw.eq("id", key).or().like("name", key));
        }

        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrs(Long categoryId) {
        List<AttrGroupEntity> attrGroupEntities = this.list(
                new QueryWrapper<AttrGroupEntity>().eq("category_id", categoryId)
        );

        List<AttrGroupWithAttrsVo> list = attrGroupEntities.stream().map(attrGroupEntity -> {
            AttrGroupWithAttrsVo vo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(attrGroupEntity, vo);
            List<AttrEntity> attrEntityList = attrService.getAttrRelation(attrGroupEntity.getId());
            vo.setAttrs(attrEntityList);
            return vo;
        }).collect(Collectors.toList());
        return list;
    }

}